package run;

import lsieun.utils.JarUtils;
import lsieun.utils.NameUtils;
import lsieun.visitor.FindInterfaceVisitor;
import org.objectweb.asm.ClassReader;

import java.lang.instrument.ClassFileTransformer;
import java.util.List;

public class A_Find_ClassFileTransformer {
    public static void main(String[] args) {
        String jarPath = PathManager.getJarPath();
        Class<?> clazz = ClassFileTransformer.class;

        List<String> jarItems = getJarItems(jarPath, clazz);
        for (String item : jarItems) {
            System.out.println(item);
        }
    }

    public static List<String> getJarItems(String jarPath, Class<?> clazz) {
        // (1) 读取Jar内的所有.class文件
        List<String> classEntries = JarUtils.getClassEntries(jarPath);

        // (2) 构造一个“过滤器”
        String targetInterfaceName = clazz.getName();
        String internalName = NameUtils.toInternalName(targetInterfaceName);
        FindInterfaceVisitor cv = new FindInterfaceVisitor(internalName);

        // (3) 进行“过滤”
        int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES | ClassReader.SKIP_CODE;
        for (String jarItem : classEntries) {
            byte[] bytes = JarUtils.readClass(jarPath, jarItem);
            if (bytes == null) continue;

            ClassReader cr = new ClassReader(bytes);
            cr.accept(cv, parsingOptions);
        }

        // (4) 返回“过滤”结果
        return cv.resultList;
    }
}
